<?php

namespace app\admin\controller\org;

use app\admin\controller\Zlog;
use app\common\controller\Backend;
use think\Db;
use think\Exception;


/**
 * 入驻申请
 *
 * @icon fa fa-circle-o
 */
class Orgreply extends Backend
{
    
    /**
     * Orgreply模型对象
     * @var \app\admin\model\org\Orgreply
     */
    protected $model = null;
    protected $searchFields = 'orgreply.name|orgreply.real_name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\org\Orgreply;
        $this->view->assign("typeList", $this->model->getTypeList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
     public function index(){
         //当前是否为关联查询
         $this->relationSearch = true;
        if($this->request->isAjax()){
            if($this->request->request('keyField')){
                return $this->selectpage();
            }
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->count();
               
            $list = $this->model
                ->with(['admin'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $key => $row) {
                $row->sort =  ($key+1+$offset);
                $row->mobile = substr_replace($row->mobile, '****', 3, 4);
            }
            $list = collection($list)->toArray();
            $result = array('total'=>$total, 'rows'=>$list);

            return json($result);

        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if (!$params['mobile'] || !\think\Validate::regex($params['mobile'], "^1\d{10}$")) {
                    $this->error(__('手机号不正确'));
                }
                $admininfo = Db::name('admin')->where('mobile', $params['mobile'])->where('org_cate_id', '>', 0)->find();
                $orginfo = Db::name('org_cate')->where('mobile', $params['mobile'])->where('parent_id', 0)->find();
                $info = $this->model->where('mobile', $params['mobile'])->find();
                if ($admininfo || $orginfo || $info) {
                    $this->error(__('该手机号已存在！'));
                }
                $orginfo2 = Db::name('org_cate')->where('name', $params['name'])->where('parent_id', 0)->find();
                $info2 = $this->model->where('name', $params['name'])->find();
                if ($orginfo2 || $info2) {
                    $this->error(__('该单位名称已存在！'));
                }
                $params['adminid'] = AID;
                $params['checktime'] = time();
                $result = $this->model->save($params);
                if ($result === false) {
                    $this->error($this->model->getError());
                }
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row= $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {
                if (!$params['mobile'] || !\think\Validate::regex($params['mobile'], "^1\d{10}$")) {
                    $this->error(__('手机号不正确'));
                }
                Db::startTrans();
                try{
                    $oldtype = $this->model->getOldData($ids);
                    $newtype = $params['type'];
                    $params['adminid'] = AID;
                    $params['checktime'] = time();
                    $result = $row->save($params);
                    if ($result === false) {
                        $this->error($row->getError());
                    }
                    if($newtype == 2){
                        Db::name('org_cate')->where('mobile', $params['mobile'])->update(['status'=>1]);
                    }
                    if($oldtype != 1 && $newtype == 1){
                        $orginfo = Db::name('org_cate')->where('mobile', $params['mobile'])->find();
                        if(!$orginfo){
                            $org['name'] = $params['name'];
                            $org['level'] = 1;
                            $org['createtime'] = time();
                            $org['mobile'] = $params['mobile'];
                            $org['linkman'] = $params['real_name'];
                            $org_cate_id =  Db::name('org_cate')->insertGetId($org);
                            if ($org_cate_id === false) {
                                $this->error('单位创建失败！');
                            }
                            $admin['is_super'] =2;
                            $admin['org_cate_id'] =$org_cate_id;
                            $admin['username'] = $params['real_name'];
                            $admin['mobile'] = $params['mobile'];
                            $admin['createtime'] = time();
                            $admin['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                            $admin_id =  Db::name('admin')->insertGetId($admin);
                            if ($admin_id === false) {
                                Db::name('org_cate')->where('id', $org_cate_id)->delete();
                                $this->error('管理员创建失败！');
                            }
                            Db::name('auth_group_access')->insertGetId(['uid'=>$admin_id,'group_id'=>4]);
                            $room = Db::name('consult_room')->where('org_cate_id', 0)->field('name,image,introduce')->select();
                            foreach ($room as &$val){
                                $val['org_cate_id'] = $org_cate_id;
                                $val['createtime'] = time();
                            }
                            Db::name('consult_room')->insertAll($room);
                        }else{
                            Db::name('org_cate')->where('mobile', $params['mobile'])->update(['status'=>0]);
                        }
                        $sms['name'] = '“'.$params['name'].'”';
                        $sms['time'] = date('Y-m-d H:i:s');
                        $alisms = new \addons\alisms\library\Alisms();
                        $config =  config('config')['alisms'];
                        $res = $alisms->mobile($params['mobile'])
                            ->template($config['template']['notice'])
                            ->sign($config['sign'])
                            ->param($sms)
                            ->send();
                        if ($res === false) {
                            $this->error('短信发送失败！');
                        }
                        $ip = request()->ip();
                        $sms = \app\common\model\Sms::create(['event' => 'orgreply', 'mobile' => $params['mobile'], 'content' => '您提交的"'. $sms['name'].'"已于'.$sms['time'].'通过审核，请等待管理员联系您。', 'ip' => $ip, 'createtime' =>time()]);
                    }
                    Db::commit();
                }catch (Exception $e){
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error();
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
